package org.jeecg.modules.apiacl.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.AppUtils;
import org.jeecg.modules.apiacl.entity.TaxApiaclAuthorize;
import org.jeecg.modules.apiacl.service.ITaxApiaclAuthorizeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;

import java.util.List;

/**
* @Description: 对外开放接口授权校验
* @Author: jeecg-boot
* @Date:   2023-08-02
* @Version: V1.0
*/
@Slf4j
public class ApiAuthorizeController{
   @Autowired
   private ITaxApiaclAuthorizeService taxApiaclAuthorizeService;

    /***
     * 对接口调用进行校验权限
     * @param app_key
     * @param app_secret
     * @return
     */
    public Boolean authorize(String app_key, String app_secret) {
        Boolean isAuthorize = false;
        if (StringUtils.isNotEmpty(app_key) && StringUtils.isNotEmpty(app_secret)) {
            String appsecret = AppUtils.getAppSecret(app_key);
            if (app_secret.equals(appsecret)) {
                isAuthorize = true;
            }
        }
        return isAuthorize;
    }
    /***
     * 对接口调用进行校验权限
     * @param headers
     * @return
     */
    public Boolean authorize(MultiValueMap<String, String> headers) {
        String app_key = getHeaderParamBykey(headers, "app_key");
        String app_secret = getHeaderParamBykey(headers, "app_secret");
        String timestamp = getHeaderParamBykey(headers, "timestamp");
        log.info("app_key:" + app_key + "app_secret:" + app_secret);
        Boolean isAuthorize = false;
        if (StringUtils.isNotEmpty(app_key) && StringUtils.isNotEmpty(app_secret)) {
            String appsecret = AppUtils.getAppSecret(app_key);
            if (app_secret.equals(appsecret)) {
                isAuthorize = true;
            }
        }
        return isAuthorize;
    }

    /***
     * 对接口调用进行校验权限
     * @param app_key
     * @param app_secret
     * @return
     */
    public  TaxApiaclAuthorize Authorize(String app_key, String app_secret){
        return taxApiaclAuthorizeService.authorize(app_key,app_secret);
    }

    /***
     * 获取请求头
     * @param headers 请求头信息
     * @param key  参数key
     * @return
     */
    public static String getHeaderParamBykey(MultiValueMap<String, String> headers, String key) {
        String param = null;
        if( headers.containsKey(key)) {
            List<String> params = headers.get(key);
            if (!params.isEmpty()) {
                param = params.get(0);
            }
        }
        return param;
    }

}
